package com.gxpt.app.view;

import android.app.Dialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.bean.createorder2_bean;
import com.gxpt.app.bean.createorder_bean;
import com.gxpt.app.bean.getallcategory_bean;
import com.gxpt.app.bean.goodsdetail_bean;
import com.gxpt.app.bean.normal;
import com.gxpt.app.bean.orderdetail_bean;
import com.utils.ScreenUtils;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.utils.picasso.PicassoUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_shopping_order_detail)
public class Activity_shopping_order_detail extends BaseActivity {

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;


    @ViewInject(R.id.txt_no)
    TextView txt_no;

    @ViewInject(R.id.txt_create_time)
    TextView txt_create_time;

    //////////////////////////收货
    @ViewInject(R.id.txt_shouhuoren)
    TextView txt_shouhuoren;

    @ViewInject(R.id.txt_phone)
    TextView txt_phone;

    @ViewInject(R.id.txt_shouhuodizhi)
    TextView txt_shouhuodizhi;

    @ViewInject(R.id.toDel)
    Button toDel;

    @ViewInject(R.id.toCancel)
    Button toCancel;

    @ViewInject(R.id.toPay)
    Button toPay;

    @ViewInject(R.id.toEvaluate)
    Button toEvaluate;

    @ViewInject(R.id.toApply)
    Button toApply;

    //
    float pay_sum =0;
    float privilege =0;//优惠金额
    float freight =0;//运费

    @ViewInject(R.id.txt_youhui)
    TextView txt_youhui;

    @ViewInject(R.id.txt_yunfei)
    TextView txt_yunfei;

    @ViewInject(R.id.txt_spjine)
    TextView txt_spjine;


    @ViewInject(R.id.txt_fapiao)
    TextView txt_fapiao;

    @ViewInject(R.id.txt_info1)
    TextView txt_info1;

    @ViewInject(R.id.txt_info2)
    TextView txt_info2;

    @ViewInject(R.id.toInvoice)
    RelativeLayout toInvoice;
//////////////////////////////////


    @ViewInject(R.id.goods_list_layout)
    LinearLayout goods_list_layout;

    orderdetail_bean.orderdetail morderdetail;


    int pic_view_width = 0;
    int pic_view_hight = 0;

    List<getallcategory_bean.getallcategory> type = null;
    getallcategory_bean toData = null;

    String[]  titles = null;
    String[]  ids = null;

    JSONArray data = new JSONArray();

    int invoice_desc = 0 ;// 0明细 1耗材 2办公用品3 电脑配件

    String invoice_title;
    String invoice_phone;
    String invoice_email;

    int has_invoice = 0 ;//0 不开 1 开具

    String detail_id;
    String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        x.view().inject(this);


        Bundle b = getIntent().getBundleExtra("DATA");
        if(b!=null){
            id = b.getString("ID");
            detail_id = b.getString("detail_id");
        }
        initView();
        initData();
    }

    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent){
        if(messageEvent.getMessageType() ==Constant.ACTION_pay_success){
            closeActivity();
        }
    }


    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_dingdanxiangqing));
        int Sviewwidth  = ScreenUtils.getScreenWidth(context);//
        pic_view_width  = Sviewwidth / 4;
        pic_view_hight  = pic_view_width/10*9;
    }

    @Override
    public void initData() {
        toNet_orderdetail();
    }


    private void init_List_main_type(){

        if(morderdetail.status ==0 || morderdetail.status== 4){//只有未支付或者已取消的订单可以删除
            toDel.setVisibility(View.VISIBLE);
        }else{
            toDel.setVisibility(View.GONE);
        }

        if(morderdetail.status ==0){//只有未支付
            toCancel.setVisibility(View.VISIBLE);
        }else{
            toCancel.setVisibility(View.GONE);
        }

        if(morderdetail.status ==0){//只有未支付
            toPay.setVisibility(View.VISIBLE);
        }else{
            toPay.setVisibility(View.GONE);
        }

        if(morderdetail.status ==3){//
            toEvaluate.setVisibility(View.VISIBLE);
            toApply.setVisibility(View.VISIBLE);
        }else{
            toEvaluate.setVisibility(View.GONE);
            toApply.setVisibility(View.GONE);
        }



        goods_list_layout.removeAllViews();

        txt_no.setText(morderdetail.order_id);
        txt_create_time.setText(morderdetail.create_time);

        txt_shouhuoren.setText(""+morderdetail.address.recipient_name);
        txt_phone.setText(""+morderdetail.address.mobile_phone);
        txt_shouhuodizhi.setText(""+morderdetail.address.province+
                morderdetail.address.city+
                morderdetail.address.region+
                morderdetail.address.detail_address);

        pay_sum = Float.parseFloat(morderdetail.pay_sum);//总价
        txt_spjine.setText(getString(R.string.txt_azongjia,""+pay_sum));

        privilege = Float.parseFloat(morderdetail.privilege);//优惠金额
        txt_youhui.setText(getString(R.string.txt_azongjia,""+privilege));

        freight = Float.parseFloat(morderdetail.freight);//运费
        txt_yunfei.setText(getString(R.string.txt_azongjia,""+freight));

        if(morderdetail.has_invoice.equals("0")){
            toInvoice.setVisibility(View.GONE);
        }else{
            toInvoice.setVisibility(View.VISIBLE);

            if(morderdetail.invoice_type.equals("0")){
                txt_fapiao.setText(""+getResources().getString(R.string.txt_geren));
                txt_info1.append(AppUtils.getInvoice(Integer.parseInt(morderdetail.invoice_desc)));
            }else{
                txt_fapiao.setText(""+getResources().getString(R.string.txt_danwei));
                txt_info1.append(morderdetail.invoice_title+"\n");
                txt_info1.append(AppUtils.getInvoice(Integer.parseInt(morderdetail.invoice_desc)));
            }

            txt_info1.append(AppUtils.getInvoice(Integer.parseInt(morderdetail.invoice_desc)));
            txt_info2.append(morderdetail.invoice_phone+"\n"+morderdetail.invoice_email);
        }

        for (int a = 0; a < morderdetail.buyinfo.size(); a++) {
            goods_list_layout.addView(creatListItemView(a));
        }
    }

    private View creatListItemView(int id) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_shopping_confirm_list, null);
        TextView txt_shop_name = (TextView)convertView.findViewById(R.id.txt_shop_name);
        txt_shop_name.setText(morderdetail.buyinfo.get(id).shop_name);

        TextView txt_shop_id = (TextView)convertView.findViewById(R.id.txt_shop_id);
        txt_shop_id.setText(morderdetail.buyinfo.get(id).shop_id);


        EditText edit_message = (EditText)convertView.findViewById(R.id.edit_message);
        edit_message.setEnabled(false);
        edit_message.setText(morderdetail.buyinfo.get(id).message);

        LinearLayout layout_sub = (LinearLayout)convertView.findViewById(R.id.layout_sub);

        if(morderdetail.buyinfo.get(id).goods != null ){
            if(morderdetail.buyinfo.get(id).goods.size()>0){
                for (int a = 0; a < morderdetail.buyinfo.get(id).goods.size(); a++) {
                    layout_sub.addView(creat_sub_goods_views(morderdetail.buyinfo.get(id).goods.get(a),a));
                }
            }
        }

        return convertView;
    }

    private View creat_sub_goods_views(orderdetail_bean.orderdetail.buyinfo_info.goods_info gs, int index) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_item_shopping_confirm_list, null);

//        Logger.i("gs.sku_id = "+gs.sku_id);

        TextView txt_gone_goods_id = (TextView)convertView.findViewById(R.id.txt_gone_goods_id);
        txt_gone_goods_id.setText(gs.goods_id);
        TextView txt_gone_sku_id = (TextView)convertView.findViewById(R.id.txt_gone_sku_id);
        txt_gone_sku_id.setText(gs.sku_id);
        TextView txt_gone_goods_num = (TextView)convertView.findViewById(R.id.txt_gone_goods_num);
        txt_gone_goods_num.setText(gs.goods_num);



        TextView txt_goods_name = (TextView)convertView.findViewById(R.id.txt_goods_name);
        txt_goods_name.setText(gs.goods_name);

        TextView txt_sku_name = (TextView)convertView.findViewById(R.id.txt_sku_name);
        txt_sku_name.setText(gs.sku_name);

        TextView txt_sell_price = (TextView)convertView.findViewById(R.id.txt_sell_price);
        txt_sell_price.setText(gs.sell_price);

        TextView txt_buy_num = (TextView)convertView.findViewById(R.id.txt_buy_num);
        txt_buy_num.setText("x "+gs.goods_num);


        ImageView img_thumb= (ImageView)convertView.findViewById(R.id.img_thumb);
        if(gs.thumb.isEmpty()){
            PicassoUtils.Picasso_displayImage(context,R.mipmap.ic_launcher,pic_view_width,pic_view_hight,img_thumb);
        }else{
            PicassoUtils.Picasso_displayImage(context,Constant.IP+"/"+gs.thumb,pic_view_width,pic_view_hight,img_thumb);
        }
        return convertView;
    }


    @Event(value={R.id.toback,R.id.toPay,R.id.toDel,R.id.toCancel,R.id.toEvaluate,R.id.toApply})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
            case R.id.toDel:
                toNet_delorder();
                break;
            case R.id.toCancel:
                toNet_cancelorder();
                break;
            case R.id.toPay:
                Bundle b = new Bundle();
                b.putString("order_id",   morderdetail.order_id);
                b.putString("total_price",morderdetail.pay_sum);
                b.putString("id",         id);
                jumpActivity(Activity_pay_shopping.class,b,false);
//
                break;
            case R.id.toEvaluate:
//                Bundle b2 = new Bundle();
//                b2.putString("column_id",   morderdetail.);
//                jumpActivity(Activity_pay_shopping.class,b2,false);
                Dialog_detail();
                break;
            case R.id.toApply:
//                Bundle b2 = new Bundle();
//                b2.putString("column_id",   morderdetail.);
//                jumpActivity(Activity_pay_shopping.class,b2,false);
                Dialog_detail_apply();
                break;
        }
    }



    Dialog dialog;
    public void Dialog_detail(){
        dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_goods_list, null);
        dialog.setContentView(view);

        TextView cancel = (TextView)view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        LinearLayout goods_list_layout2 = (LinearLayout)view.findViewById(R.id.goods_list_layout);

        for(int a=0;a < morderdetail.buyinfo.size();a++){

            orderdetail_bean.orderdetail.buyinfo_info shoplist = morderdetail.buyinfo.get(a);

            for(int b=0;b < shoplist.goods.size();b++){

                goods_list_layout2.addView(creatListItemView(shoplist.goods.get(b)));
            }
        }


        Window dialogWindow = dialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }

    private View creatListItemView(orderdetail_bean.orderdetail.buyinfo_info.goods_info info) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_goods_xiajia_list, null);

        TextView list_id = (TextView)convertView.findViewById(R.id.list_id);
        TextView list_title   = (TextView)convertView.findViewById(R.id.list_title);

        list_id.setText(info.goods_id);
        list_title.setText(info.sku_name);
        convertView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {

                TextView list_id = (TextView)v.findViewById(R.id.list_id);
//                Logger.d("---"+list_id.getText());
                dialog.dismiss();
                Bundle b = new Bundle();
                b.putString("column_id",""+list_id.getText().toString());
                jumpActivity(Activity_evaluate_goods.class,b,true);

            }
        });
        return convertView;
    }


    Dialog dialog2;
    public void Dialog_detail_apply(){
        dialog2=new Dialog(context,R.style.customDialogStyle);
        dialog2.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_apply_list, null);
        dialog2.setContentView(view);

        TextView cancel = (TextView)view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        LinearLayout goods_list_layout2 = (LinearLayout)view.findViewById(R.id.goods_list_layout);

        for(int a=0;a < morderdetail.buyinfo.size();a++){

            orderdetail_bean.orderdetail.buyinfo_info shoplist = morderdetail.buyinfo.get(a);

            for(int b=0;b < shoplist.goods.size();b++){

                goods_list_layout2.addView(creatListItemView_apply(shoplist.goods.get(b),
                        morderdetail.detail_id));
            }
        }


        Window dialogWindow = dialog2.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog2.show();

    }

    private View creatListItemView_apply(orderdetail_bean.orderdetail.buyinfo_info.goods_info info,String detail_id) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_goods_xiajia_list, null);

        TextView list_id = (TextView)convertView.findViewById(R.id.list_id);
        TextView list_id_detail = (TextView)convertView.findViewById(R.id.list_id_detail);
        TextView list_title   = (TextView)convertView.findViewById(R.id.list_title);

        list_id_detail.setText(detail_id);
        list_id.setText(info.goods_id);
        list_title.setText(info.sku_name);
        convertView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {

                TextView list_id = (TextView)v.findViewById(R.id.list_id);
                TextView list_id_detail = (TextView)v.findViewById(R.id.list_id_detail);
//                Logger.d("---"+list_id.getText());
                dialog2.dismiss();
                Bundle b = new Bundle();
                b.putString("detail_id",""+list_id_detail.getText().toString());
                b.putString("column_id",""+list_id.getText().toString());
                jumpActivity(Activity_apply_goods.class,b,true);

            }
        });
        return convertView;
    }


    //////NET DO
    StringCallback do_orderdetail = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e(s);
            try{
                orderdetail_bean data = new Gson().fromJson(s, orderdetail_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    if(data.data != null){
                        morderdetail = data.data;
                        init_List_main_type();

                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

    /////NET
    private void toNet_orderdetail(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shoporder");
            jsonBody.put("serviceName",          "orderdetail");

            jsonBody.put("member_id",            AppUtils.get_user_id(context));
            jsonBody.put("id",                   id);
            jsonBody.put("detail_id",            detail_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }

//        Logger.i(jsonBody.toString()+"  ["+Constant.URL_orderdetail+"]");
        HttpUtils.http_post_string(Constant.URL_orderdetail,jsonBody.toString(),do_orderdetail);
    }

    /////NET
    private void toNet_cancelorder(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shoporder");
            jsonBody.put("serviceName",          "cancelorder");

            jsonBody.put("member_id",          AppUtils.get_user_id(context));
            jsonBody.put("id",                 id);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Logger.i(jsonBody.toString()+"  ["+Constant.URL_cancelorder+"]");
        HttpUtils.http_post_string(Constant.URL_cancelorder,jsonBody.toString(),do_cancelorder);
    }


    StringCallback do_cancelorder = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e(s);/
            try{
                normal data = new Gson().fromJson(s, normal.class);
                if(data.state !=1){
                    T.show(context,data.msg,0);
                }else{
                    EventBus.getDefault().post(new MessageEvent(Constant.ACTION_order_cancel_or_delete));
                    closeActivity();
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

    private void toNet_delorder(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shoporder");
            jsonBody.put("serviceName",          "delorder");

            jsonBody.put("member_id",          AppUtils.get_user_id(context));
            jsonBody.put("id",                 id);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Logger.i(jsonBody.toString()+"  ["+Constant.URL_delorder+"]");
        HttpUtils.http_post_string(Constant.URL_delorder,jsonBody.toString(),do_delorder);
    }


    StringCallback do_delorder = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e(s);/
            try{
                normal data = new Gson().fromJson(s, normal.class);
                if(data.state !=1){
                    T.show(context,data.msg,0);
                }else{
                    EventBus.getDefault().post(new MessageEvent(Constant.ACTION_order_cancel_or_delete));
                    closeActivity();
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
}
